#!/usr/local/bin/php
<?php
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once OPEN_LIB_PATH . '/open/models/OaCompanyModel.php';
require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';

$logger = Log::factory('console', '', '', array(
    'lineFormat' => '[%1$s] [%3$s] %5$s(%6$s): %4$s',
    'timeFormat' => '%Y-%m-%d %H:%M:%S'
), PEAR_LOG_INFO);
$logger->setPriority(PEAR_LOG_INFO);
$dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
$db = OpDbModel::getInstance($dbConfig, $logger);
$companyTable = new OpTableModel($db, 'company', $logger);
$companyModel = new OaCompanyModel($logger);
$appModel = new OaAppModel(OaAppModel::APP_CONFIG_ENV_PRODUCTION, $logger);

$companys = $companyModel->getCompanyList();
foreach ($companys as $company) {
    $companyId = (int) $company['id'];
    $apps = $appModel->getCompanyApps($companyId);
    if ($apps === false) {
        $logger->err("get company apps failed: company-$companyId");
        exit();
    }
    if (count($apps) > 0) {
        $joinStatus = 2;
    } else {
        $joinStatus = 0;
    }
    $releaseStatus = 0;
    foreach ($apps as $app) {
        if ($app['status'] == OaAppModel::APP_STATUS_IN_OPERATION) {
            $releaseStatus = 2;
            break;
        }
    }
    if ($company['grade'] >= 100) {
        $grade = 0;
    } else {
        $grade = (int) $company['grade'];
    }
    if (!$companyTable->update(array(
        'id' => $companyId
    ), array(
        'join_status' => $joinStatus,
        'release_status' => $releaseStatus,
        'grade' => $grade
    ))) {
        $logger->err("update failed: company-$companyId");
        exit();
    } else {
        $logger->info("update succeed: company-$companyId, join_status-$joinStatus, release_status-$releaseStatus");
    }
}
